// 引入mysql模块
var models = require('../db');
var express = require('express');
const mysql = require('mysql');
var router = express.Router();

var conn = mysql.createConnection(models.mysql);
conn.connect();


// 连接数据库
conn.connect((err) => {
  if (err) {
    console.error('Error connecting to database: ' + err.stack);
    return;
  }
  console.log('Connected to database as id ' + conn.threadId);
});
//已经执行到这里了
// 查询某个表格的数据
conn.query('SELECT * FROM wuliaoqitao', (error, results, fields) => {
  if (error) throw error;
  

  // 处理查询结果
  results.forEach((item) => {
    // 计算增值税后的价格（假设增值税率为10%）
    if(item.item_state === "未开始加工" ){
    const taxIncludedPrice = item.process1+item.process2+ item.process3+ item.process4+ item.process5+ item.process6+ item.process7+ item.process8+ item.process9+ item.process10; // 增值税率为10%

    // 更新数据库中的数据
    const updateSQL = 'UPDATE wuliaoqitao SET Remaining_time_for_completion = ? WHERE number = ?';
    const updateData = [taxIncludedPrice, item.number];

    conn.query(updateSQL, updateData, (err, result) => {
      if (err) throw err;
      console.log(`Updated item ${item.number}: new value = ${taxIncludedPrice}`);
      // 结束数据库连接（没写）

    });}


else if(item.item_state === "加工中"){ 

  let processProperties = ['process1', 'process2', 'process3', 'process4', 'process5', 'process6', 'process7', 'process8', 'process9', 'process10'];
  let taxIncludedPrice = 0;
  for (let i = item.process_state-1; i < processProperties.length; i++) {  
    taxIncludedPrice += item[processProperties[i]]; // 使用processProperties数组中的属性名来访问item对象的属性  
}  
  //const taxIncludedPrice = item.process1+item.process2+ item.process3+ item.process4+ item.process5+ item.process6+ item.process7+ item.process8+ item.process9+ item.process10; // 增值税率为10%

  // 更新数据库中的数据
  const updateSQL = 'UPDATE wuliaoqitao SET Remaining_time_for_completion = ? WHERE number = ?';
  const updateData = [taxIncludedPrice, item.number];

  conn.query(updateSQL, updateData, (err, result) => {
    if (err) throw err;
    console.log(`Updated item ${item.number}: new value = ${taxIncludedPrice}`);
    // 结束数据库连接（没写）

  });}
else {
  console.log("error")
}



  });


});

module.exports = router;
//以上代码是单独实现查找数据库中数据的。
